package cn.zy.company.servlet.admin;



import cn.zy.company.entity.User;
import cn.zy.company.service.UserService;
import cn.zy.company.util.Md5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/admin/editUser")
public class EditUserServlet extends HttpServlet {
    UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String id = req.getParameter("id");
            if (id != null && id != "") {
                User user = userService.findById(Integer.valueOf(id));
                req.setAttribute("data", user);
                req.getRequestDispatcher("/WEB-INF/jsp/admin/editUser.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Integer id = Integer.valueOf(req.getParameter("id"));
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String s = Md5Util.MD5(password);
            User user = new User(username, s);
            user.setId(id);
            userService.update(user);
            resp.sendRedirect("showUser");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
